//
//  MallViewController.m
//  FlowerRainGround
//
//  Created by lanou on 16/4/25.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "MallViewController.h"
#import "headIvewModel.h"//头视图的模型
#import "JingListModel.h"
#import "JIngListTableViewCell.h"
#import "MallCollectionViewCell.h"
#import "MallSectionModel.h"
#import "MallCollectionReusableView.h"
#import "MallSecondSectionCollectionReusableView.h"
#import "JingShowViewController.h"

#import "ShowSearchViewController.h"

@interface MallViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate>

@property (nonatomic, strong) headIvewModel *headModel;//头视图模型
@property (strong, nonatomic) IBOutlet UITableView *jingListTableVIew;//精选的tabelView
@property (nonatomic, strong) UICollectionView *collectionView;//商城的视图
@property (nonatomic, strong) UIScrollView *scrollerView;//整个滚动视图
@property (nonatomic, assign) NSInteger sorceTyep;
@property (nonatomic, strong) NSMutableArray *JingListArray;//精选的数组
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIView *searchView;//承载搜索框的视图
@property (nonatomic, strong) UISearchBar *searchBar;//搜索框
@property (nonatomic, strong) NSMutableArray *mallMarray;

@property (nonatomic, strong) UICollectionViewFlowLayout *flowlayout;
@property (nonatomic, strong) NSMutableArray *sectionArray;
@end

@implementation MallViewController
- (NSMutableArray *)sectionArray
{
    if (!_sectionArray) {
        _sectionArray = @[].mutableCopy;
    }
    return _sectionArray;
}
- (NSMutableArray *)JingListArray{
    if (!_JingListArray) {
        _JingListArray = [[NSMutableArray alloc] initWithCapacity:0];
        
    }
    return _JingListArray;
}



- (NSMutableArray *)mallMarray{
    if (!_mallMarray) {
        _mallMarray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _mallMarray;
}






//头视图请求
- (void) requestData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:@"http://ec.htxq.net/rest/htxq/index/carousel" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        
        for (NSDictionary *dic1 in dic[@"result"]) {
            _headModel = [[headIvewModel alloc] init];
            [_headModel setValuesForKeysWithDictionary:dic1];
            
        }
        

       dispatch_async(dispatch_get_main_queue(), ^{
           [self creatHeadImage];
           
       });
 
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

//tableView的数据请求
- (void) requestDataForJinglistTable
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer =[AFHTTPResponseSerializer serializer ];
    [manager GET:JingList parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        
        //再次点击将之前的数据清空
        [self.JingListArray removeAllObjects];
        
        NSArray *array = dic[@"result"];
        for (NSDictionary *dic1 in array) {
            JingListModel *jinglist = [[JingListModel alloc] init];
            [jinglist setValuesForKeysWithDictionary:dic1];
            
            //商品
            for (NSDictionary *dic2 in dic1[@"skuList"]) {
                GoodsModel *good = [[GoodsModel alloc] init];
                [good setValuesForKeysWithDictionary:dic2];
                jinglist.goodsmodel = good;
            }
           
            [self.JingListArray addObject:jinglist];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.jingListTableVIew reloadData];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
     
}


//商城的collectionView
- (void) requestMallData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:Mall parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       
        //再次点击将之前的数据清空
        [self.mallMarray removeAllObjects];
        
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        NSArray *array = dic[@"result"];

        for (NSDictionary  *dic1 in  array  ) {
            //分区
            MallSectionModel *mallSectonModel = [[MallSectionModel alloc] init];
            [mallSectonModel setValuesForKeysWithDictionary:dic1];
            
            [self.sectionArray addObject:mallSectonModel];
            
            NSMutableArray *temp = [NSMutableArray array];
            //商城的内容
            for (NSDictionary *dic2 in dic1[@"childrenList"]) {
                MallModel *model = [[MallModel alloc] init];
                [model setValuesForKeysWithDictionary:dic2[@"pGoods"]];
                mallSectonModel.mallModel = model;
                [temp addObject:model];
            }
            [self.mallMarray addObject:temp];
            
        }
  
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestData];
    [self creatTableView];
    [self requestMallData];
//    self.navigationController.navigationBar.translucent = NO;
    
    
    UIButton *button= [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 20, 20);
    [button setBackgroundImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    button.block = ^{
        [self search];
    };
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = right;
    

}

- (void)search{
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, 2, 300, 40)];
    _searchBar.delegate = self;
    _searchBar.placeholder = @"请输入搜索内容";
    [_searchBar setImage:[UIImage imageNamed:@"search"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    self.searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, kWidth, 44)];
    self.searchView.backgroundColor = [UIColor lightGrayColor];
    
    //右侧的button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(320, 2, 40, 40);
    [button setTitle:@"取消" forState:UIControlStateNormal];
    button.block = ^(){
        [self cancelSearch];
    };
    
    [self.searchView addSubview:button];
    
    
    [self.searchView addSubview:_searchBar];
    [self.navigationController.view addSubview:self.searchView];
   
    
}

//点击取消按钮
- (void)cancelSearch{
    [self.searchView removeFromSuperview];
    
}

//点击键盘搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self.searchBar resignFirstResponder];
    [self.searchView removeFromSuperview];
    ShowSearchViewController *showVC = [[ShowSearchViewController alloc] init];
    showVC.searchTitile = self.searchBar.text;
    showVC.fnArray = self.mallMarray;
    [self.navigationController pushViewController:showVC animated:YES];
}


#pragma mark----------头视图----------
- (void)creatHeadImage {
    

    _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 260)];
    _headerView.backgroundColor = [UIColor yellowColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 200)];
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.headModel.fnImageUrl]];
    [_headerView addSubview:imageView];
    
    
    UIView *choseheadView = [[UIView alloc] initWithFrame:CGRectMake(0, imageView.frame.size.height, kWidth, 60)];
    UIButton *jingListButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [jingListButton setTitle:@"精选" forState:UIControlStateNormal];
    jingListButton.titleLabel.font = [UIFont systemFontOfSize:20];
    jingListButton.frame = CGRectMake(60, 10, (kWidth - 180) / 2, 40);
    [choseheadView addSubview:jingListButton];
    jingListButton.block = ^(){
    
        [self creatTableView];//创建tableView
    };
    
    UIButton *mallButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [mallButton setTitle:@"商城" forState:UIControlStateNormal];
    mallButton.titleLabel.font = [UIFont systemFontOfSize:20];
    mallButton.frame = CGRectMake(120 + (kWidth - 180) / 2 , 10, (kWidth - 180) / 2, 40);
    mallButton.block = ^(){
        [self creatCollectView];
    };
    [choseheadView addSubview:mallButton];
    [choseheadView addSubview:mallButton];
    
    
    [_headerView addSubview:choseheadView];
    self.jingListTableVIew.tableHeaderView = _headerView;
    
 
}

//点击精选创建tableView
- (void) creatTableView{
    
    //在点击精选时将商城的数据清空，请求精选的数据
//    [self.mallMarray removeAllObjects];
    [self requestDataForJinglistTable];
     self.jingListTableVIew = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 49) style:(UITableViewStylePlain)];
     self.jingListTableVIew.delegate =self;
     self.jingListTableVIew.dataSource = self;
    self.jingListTableVIew.tableHeaderView = self.headerView;
    
    //注册cell
    [self.jingListTableVIew registerNib:[UINib nibWithNibName:@"JIngListTableViewCell" bundle:nil] forCellReuseIdentifier:@"reuse"];
     [self.view addSubview:self.jingListTableVIew];
    
}

#pragma mark-----tableViewDelegate--------
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.JingListArray.count;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 240;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *string = @"reuse";
    JingListModel *model = self.JingListArray[indexPath.row];
    JIngListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[JIngListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    cell.jingModel = model;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    JingShowViewController *jingVC = [[JingShowViewController alloc] init];
    jingVC.jingModel = self.JingListArray[indexPath.row];
    jingVC.typeID = 0;
    [self.navigationController pushViewController:jingVC animated:YES];
}







#pragma mark-----collectorDelegate--------
- (void) creatCollectView
{
    //再点击商城时将精选的数据删除，请求商城的数据
    [self.JingListArray removeAllObjects];

    _flowlayout = [[UICollectionViewFlowLayout alloc] init];
    _flowlayout.headerReferenceSize = CGSizeMake(kWidth, 300);
    _flowlayout.minimumInteritemSpacing = 10;
    _flowlayout.minimumLineSpacing = 10;
    _flowlayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    _flowlayout.itemSize = CGSizeMake((kWidth - 30)/2, 200);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 49) collectionViewLayout:_flowlayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    //注册cell
    [self.collectionView registerClass:[MallCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reuse"];//第一个分区的视图
    [self.collectionView registerNib:[UINib nibWithNibName:@"MallCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"reuse"];//注册cell
    [self.collectionView registerClass:[MallSecondSectionCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];//第二三个分区的视图
    [self.view addSubview:self.collectionView];
}

//分区的个数
- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    

    return self.sectionArray.count;
}

//每个分区的item
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    NSInteger num = [self.mallMarray[section] count];
    return num;
    
    

  
}


//cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *string = @"reuse";
    MallCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:string forIndexPath:indexPath];
    
    MallModel *model = [MallModel new];
    model = self.mallMarray[indexPath.section][indexPath.row];

    //给cell赋值
    [cell.backgroundImage sd_setImageWithURL:[NSURL URLWithString:model.fnAttachment1]];
    cell.fnEnNameLabel.text = model.fnEnName;
    cell.fnNameLabel.text = model.fnName;
    cell.priceLabel.text = [NSString stringWithFormat:@"￥%ld", model.fnMarketPrice];
    

    return cell;
}




- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section == 0) {
        _flowlayout.headerReferenceSize = CGSizeMake(kWidth, 300);
        MallCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reuse" forIndexPath:indexPath];
        [view addSubview:self.headerView];
        view.backgroundColor = [UIColor whiteColor];
       MallSectionModel *model = self.sectionArray[indexPath.section];
        view.headerlabel.text = model.fnName;
        return view;
    
    }else{
        _flowlayout.headerReferenceSize = CGSizeMake(kWidth, 60);
        MallSecondSectionCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head" forIndexPath:indexPath];
        //找到大模型
        MallSectionModel *model = self.sectionArray[indexPath.section];
        view.headerlabel.text = model.fnName;
        return view;
    }
    
    return nil;

    
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    JingShowViewController *jingVC = [[JingShowViewController alloc] init];
    jingVC.mallmodel = self.mallMarray[indexPath.section][indexPath.row];
    jingVC.typeID = 1;
    [self.navigationController pushViewController:jingVC animated:YES];
    
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
